#include "pool_head.h"
#define SON_NUMS 4
#define EVS_LEN 10

int pipe_fd[2];
void func(int num){
    write(pipe_fd[1],"1",1);
}
int main(){
    process_t list[SON_NUMS]; //创建一个数组
    init_pool(list,SON_NUMS); //初始化进程池
    pipe(pipe_fd); //创建管道

    int sockfd;
    init_socket(&sockfd,"8080","192.168.52.128");

    int epfd = epoll_create(1);
    add_epoll(epfd,sockfd);

    signal(2,func); //注册2号信号

    add_epoll(epfd,pipe_fd[0]); //将管道的读端也加入到epoll树上
    struct epoll_event evs[EVS_LEN];
    while(1){
        memset(evs,0,sizeof(evs));
        int num = epoll_wait(epfd,evs,EVS_LEN,-1);
        for(int i = 0; i < num; ++i){
            int cur_fd = evs[i].data.fd;
            if(cur_fd == sockfd){
                //有新的连接
                int new_fd = accept(sockfd,NULL,NULL);
                printf("新的连接文件描述符:%d\n",new_fd);
                //将新的连接发送给子进程
                send_to_son(list,new_fd,SON_NUMS);
                close(new_fd);
            }else if(cur_fd == pipe_fd[0]){
                //进程需要退出
                char buf[5] = {0};
                read(pipe_fd[0],buf,sizeof(buf));

                for(int i = 0; i < SON_NUMS; ++i){
                    //通知子进程全部退出
                    send_message(list[i].local_sockfd,1,-1);
                }

                for(int i = 0; i < SON_NUMS; ++i){
                    //等待子进程退出
                    wait(NULL);
                }
                printf("子进程全部退出，父进程退出...\n");
                close(sockfd);
                close(pipe_fd[0]);
                close(epfd);
                exit(0);
            }

            for(int i = 0; i < SON_NUMS; ++i){
                //说明是子进程发来的消息
                if(cur_fd == list[i].local_sockfd){
                    char buf[5] = {0};
                    read(cur_fd,buf,sizeof(buf));
                    list[i].flag = FREE;
                    break;
                }
            }
        }
    }
    return 0;
}